package com.onlinescxhz.demo.config;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.onlinescxhz.demo.Mapper.UserMapperDao;
import com.onlinescxhz.demo.pojo.User;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtInterceptor implements HandlerInterceptor {
    @Resource
    private UserMapperDao userMapperDao;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token=request.getHeader("token");
        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 执行认证
        if (StrUtil.isBlank(token)) {
            return false;
        }
        // 获取 token 中的 user id
        String username="";
        try {
            username = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new RuntimeException("404");
        }

        // 根据token中的userid查询数据库
        User user =null;
        try {
            user=userMapperDao.findbyusername(username);
            if(user==null)
                return false;
        } catch (Exception e) {

        }


        //JWTVerifier jwtVerifier= JWT.require(Algorithm.HMAC256(user.getUserpwd())).build();;
        //DecodedJWT decodedJWT=null;
        try {
            //decodedJWT=jwtVerifier.verify(token); // 验证token
            Algorithm algorithm = Algorithm.HMAC256(user.getPassword());
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            //return true;
        } catch (Exception e) {

        }
        return true;
    }


}
